package cn.xsly.system.service.impl;

import cn.xsly.system.domain.Role;
import cn.xsly.system.mapper.MenuMapper;
import cn.xsly.system.mapper.RoleMapper;
import cn.xsly.system.service.IRoleService;
import cn.xsly.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void add(Role role) {
    super.add(role);
        addRoleMenuAndPermission(role);
    }



    @Override
    @Transactional
    public void delete(Long id) {
    //需要先删除中间表才能删除角色表
        roleMapper.delRoleMenu(id);
        roleMapper.delRoleRermission(id);
        roleMapper.delRoleEmployee(id);
        super.delete(id);

    }

    @Override
    @Transactional
    public void update(Role role) {
        super.update(role);
        roleMapper.delRoleMenu(role.getId());
        roleMapper.delRoleRermission(role.getId());
        roleMapper.delRoleEmployee(role.getId());
        addRoleMenuAndPermission(role);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        for(Long id:ids){
            delete(id);
        }
    }
    //添加角色菜单和权限
    private void addRoleMenuAndPermission(Role role) {
        List<Long> menus = role.getMenus();
        if(menus.size()>0){
            //选择菜单下面多个管理权限进行保存
            roleMapper.addRoleMenu(role);
        }
        List<Long> permissions = role.getPermissions();
        if(permissions.size()>0){
            roleMapper.addPermission(role);
        }
    }
}
